﻿using System;
using System.Collections.Generic;
using System.Text;
using MediatR;
using Casamiel.Domain;
using Casamiel.Infrastructure;
using Casamiel.Domain.Request;
using Casamiel.Domain.Response;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.Domain.Request.IC;

using Casamiel.Domain.Entity;
using Casamiel.Common;
using Microsoft.Extensions.Options;

namespace Casamiel.Application.Commands
{
    /// <summary>
	/// 
	/// </summary>
    public sealed class CancelMemberCouponCommandHandler : IRequestHandler<CancelMemberCouponCommand, BaseResult<string>>
    {

        private readonly IMemberCouponRecordRepository  _couponRecordRepository;
        private readonly INetICService _netICService;
		private readonly CasamielSettings _casamielSettings;
			/// <summary>
			/// 
			/// </summary>
			/// <param name="memberCouponRecordRepository"></param>
			/// <param name="netICService"></param>
			public CancelMemberCouponCommandHandler(IMemberCouponRecordRepository memberCouponRecordRepository,INetICService netICService, IOptionsSnapshot<CasamielSettings> settings)
        {
			if (settings is null) {
				throw new ArgumentNullException(nameof(settings));
			}

			_couponRecordRepository = memberCouponRecordRepository;
            _netICService = netICService;
			_casamielSettings = settings.Value;

		}
        public async Task<BaseResult<string>> Handle(CancelMemberCouponCommand request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
			
			if (_casamielSettings.ApiName == "hgspApi") {
				return new BaseResult<string>("", 0, "");
			}
			MemberCouponRecord entity;
            if (request.RefundMode == 0)
            {
               entity = await _couponRecordRepository.FindAsync<ICasaMielSession>(request.ActivityId, request.CardNO).ConfigureAwait(false);
            }
            else
            {
                entity = await _couponRecordRepository.FindByCorderCodeAsync<ICasaMielSession>(request.ActivityId, request.OrderCode).ConfigureAwait(false);
            }
           
            if (entity != null)
            {
                var req = new TicketLargessCancelReq { Largessno = entity.Largessno };
                var d = await _netICService.Icticketlargesscancel(req).ConfigureAwait(false);
                if (d.code == 0)
                {
                    entity.Status = 0;
                    await _couponRecordRepository.UpdateAsync<ICasaMielSession>(entity).ConfigureAwait(false);
                    
                }
                return new BaseResult<string>("", d.code, d.msg);

            }
            else
            {
                return new BaseResult<string>("",0, "未领券");
            }
             
        }
    }
}
